package com.nineclock.system.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nineclock.common.entity.PageResult;
import com.nineclock.common.enums.ResponseEnum;
import com.nineclock.common.exception.NcException;
import com.nineclock.common.threadLocal.CurrentUserHolder;
import com.nineclock.common.utils.BeanHelper;
import com.nineclock.system.dto.SysCompanyUserDTO;
import com.nineclock.system.easyexcel.ExcelMember;
import com.nineclock.system.easyexcel.ExcelMemberListener;
import com.nineclock.system.mapper.*;
import com.nineclock.system.pojo.*;
import com.nineclock.system.service.SysCompanyUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class SysCompanyUserServiceImpl implements SysCompanyUserService {

    @Autowired
    private SysCompanyUserMapper sysCompanyUserMapper;

    //获取企业管理员信息
    @Override
    public SysCompanyUserDTO getCurrentAdmin() {
        //获取当前企业id
        Long companyId = CurrentUserHolder.get().getCompanyId();

        SysCompanyUser companyUserAdmin = sysCompanyUserMapper.getCurrentAdmin(companyId);

        //健壮性判断是否为空
        if (companyUserAdmin == null) {
            throw new NcException(ResponseEnum.COMPANY_ADMIN_NOT_EXISTS);
        }

        return BeanHelper.copyProperties(companyUserAdmin, SysCompanyUserDTO.class);
    }

    /**
     * 获取组企业员工
     */
    @Override
    public List<SysCompanyUserDTO> listSysCompanyUser() {

        //获取企业id
        Long companyId = CurrentUserHolder.get().getCompanyId();

        LambdaQueryWrapper<SysCompanyUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysCompanyUser::getCompanyId, companyId);
        queryWrapper.eq(SysCompanyUser::getEnable, 1);

        //查询有用数据
        List<SysCompanyUser> sysCompanyUsers = sysCompanyUserMapper.selectList(queryWrapper);


        return BeanHelper.copyWithCollection(sysCompanyUsers, SysCompanyUserDTO.class);
    }

    /**
     * 分页查询部门下的员工数据列表
     */
    @Autowired
    private SysDepartmentDTOMapper departmentDTOMapper;

    @Override
    public PageResult<SysCompanyUserDTO> members(Integer page, Integer pageSize, String keyword, Long departmentId) {
        //存储部门父类及其子类的id
        List<Long> departmentIds = new ArrayList<>();
        if (departmentId != 0) {
            departmentIds.add(departmentId);
        }

        //查找子部门集合
        this.queryChildrenDepartmentIds(departmentIds, departmentId);

        //分页参数
        Page<SysCompanyUser> companyUserPage = new Page<>(page, pageSize);
        //其他条件
        LambdaQueryWrapper<SysCompanyUser> wrapper = new LambdaQueryWrapper<>();
        if (keyword != null && keyword.length() > 0) {
            wrapper.and(wrapper1 -> {
                wrapper1.like(SysCompanyUser::getUserName, keyword)
                        .or().like(SysCompanyUser::getMobile, keyword)
                        .or().like(SysCompanyUser::getWorkNumber, keyword);
            });
        }
        //企业id
        wrapper.eq(SysCompanyUser::getCompanyId, CurrentUserHolder.get().getCompanyId());
        //部门id集合
        wrapper.in(SysCompanyUser::getDepartmentId, departmentIds);

        Page<SysCompanyUser> userPageList = sysCompanyUserMapper.selectPage(companyUserPage, wrapper);
        //获取要展示的数据
        List<SysCompanyUser> listRecords = userPageList.getRecords();
        //判断要展示的数据是否为空
        if (CollectionUtil.isNotEmpty(listRecords)) {
            List<SysCompanyUserDTO> records = BeanHelper.copyWithCollection(listRecords, SysCompanyUserDTO.class);
            //如果不为空封装到PageResult中
            PageResult<SysCompanyUserDTO> pageResult = new PageResult<>();

            pageResult.setTotalPage(userPageList.getPages());
            pageResult.setTotal(userPageList.getTotal());
            pageResult.setRows(records);
            return pageResult;
        }

        return new PageResult<>();
    }

    //查找子部门集合
    public void queryChildrenDepartmentIds(List<Long> departmentIds, Long departmentId) {
        LambdaQueryWrapper<SysDepartment> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysDepartment::getCompanyId, CurrentUserHolder.get().getCompanyId());
        wrapper.eq(SysDepartment::getParentId, departmentId);
        //获取所有的子列表
        List<SysDepartment> departmentList = departmentDTOMapper.selectList(wrapper);
        //判断是否为空
        if (CollectionUtil.isNotEmpty(departmentList)) {
            //抽取部门id
            //map映射
            //collect:转换成指定的集合类型
            List<Long> ids = departmentList.stream().map(department -> {
                return department.getId();
            }).collect(Collectors.toList());
            //将子列表添加到departmentIds中
            departmentIds.addAll(ids);
            for (Long id : ids) {
                this.queryChildrenDepartmentIds(departmentIds, id);
            }
        }

    }

    /**
     * 直接导入:直接导入企业员工信息
     */
    @Override
    public void uploadExcel(MultipartFile excelFile) throws IOException {
        if (excelFile == null) {
            throw new NcException(ResponseEnum.INVALID_PARAM_ERROR);
        }

        EasyExcel.read(excelFile.getInputStream(), ExcelMember.class, new ExcelMemberListener(this)).sheet(0).doRead();

    }


    /**
     * 解析每一行数据
     */
    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysCompanyUserRoleMapper sysCompanyUserRoleMapper;
    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Override
    public void handleParsedData(List<ExcelMember> excelMemberList) {

        //健壮性判断
        if (excelMemberList != null) {
            for (ExcelMember excelMember : excelMemberList) {
                //健壮性判断手机号和邮箱是否哦重复
                LambdaQueryWrapper<SysUser> userQW = new LambdaQueryWrapper<>();
                userQW.eq(SysUser::getMobile, excelMember.getMobile())
                        .or()
                        .eq(SysUser::getEmail, excelMember.getEmail());
                Integer userCount = sysUserMapper.selectCount(userQW);
                if (userCount > 0) {
                    throw new NcException(ResponseEnum.USER_MOBILE_EMAIL_EXISTS);
                }
                //判断工号是否重复
                LambdaQueryWrapper<SysCompanyUser> companyUserQW = new LambdaQueryWrapper<>();
                companyUserQW.eq(SysCompanyUser::getWorkNumber, excelMember.getWorkNumber());
                companyUserQW.eq(SysCompanyUser::getCompanyId, CurrentUserHolder.get().getCompanyId());
                Integer companyUserCount = sysCompanyUserMapper.selectCount(companyUserQW);
                if (companyUserCount > 0) {
                    throw new NcException(ResponseEnum.WROK_NUM_EXISTS);
                }

                //将数据写入用户表
                SysUser sysUser = new SysUser();
                sysUser.setUsername(excelMember.getName());//用户名
                sysUser.setPassword(new BCryptPasswordEncoder().encode("123456")); //设置初始密码
                sysUser.setMobile(excelMember.getMobile());//手机号
                sysUser.setEmail(excelMember.getEmail()); //用户Email
                sysUser.setCreateTime(new Date()); //创建日期
                sysUser.setStatus((short) 1); //用户状态可用
                sysUser.setLastLoginCompanyId(CurrentUserHolder.get().getCompanyId());//企业id
                sysUserMapper.insert(sysUser);

                //将数据写入企业
                SysCompanyUser companyUser = new SysCompanyUser();
                companyUser.setCompanyName(CurrentUserHolder.get().getCompanyName());//企业名称
                companyUser.setCompanyId(CurrentUserHolder.get().getCompanyId());//企业id
                companyUser.setUserId(sysUser.getId());//用户id
                companyUser.setPost(excelMember.getPosition()); //岗位
                companyUser.setWorkNumber(excelMember.getWorkNumber());//工号
                companyUser.setEmail(excelMember.getEmail());//email
                companyUser.setOfficeAddress(excelMember.getWorkAddr());//办公位置
                companyUser.setTimeEntry(new Date()); //入职时间
                companyUser.setRemark(excelMember.getDesc());//备注
                companyUser.setEnable((short) 1);//是否有效
                companyUser.setCreateTime(new Date()); //创建时间
                companyUser.setMobile(excelMember.getMobile());//手机号
                companyUser.setUserName(sysUser.getUsername());//用户名

                //根据企业id和部门名称获取部门id
                LambdaQueryWrapper<SysDepartment> departmentQW = new LambdaQueryWrapper<>();
                departmentQW.eq(SysDepartment::getCompanyId, CurrentUserHolder.get().getCompanyId());//企业id
                departmentQW.eq(SysDepartment::getName, excelMember.getDepartmentName());//企业名称
                SysDepartment sysDepartment = departmentDTOMapper.selectOne(departmentQW);
                //健壮性判断如果部门不为空
                if (sysDepartment != null) {
                    companyUser.setDepartmentId(sysDepartment.getId());//部门id
                    companyUser.setDepartmentName(sysDepartment.getName());//部门名称
                }
                //保存员工信息
                sysCompanyUserMapper.insert(companyUser);
                LambdaQueryWrapper<SysRole> roleQw = new LambdaQueryWrapper<>();
                //通过企业id和角色名称查询角色
                roleQw.eq(SysRole::getCompanyId, CurrentUserHolder.get().getCompanyId());
                roleQw.eq(SysRole::getRoleName, excelMember.getRoleName());//角色名称

                SysRole sysRole = sysRoleMapper.selectOne(roleQw);
                if (sysRole != null) {
                    SysCompanyUserRole companyUserRole = new SysCompanyUserRole();
                    companyUserRole.setCompanyUserId(CurrentUserHolder.get().getCompanyUserId());
                    companyUserRole.setRoleId(sysRole.getId()); //角色id
                    companyUserRole.setCompanyUserId(companyUser.getId()); //员工id
                    //保存员工权限
                    sysCompanyUserMapper.insert(companyUser);
                }
            }
        }


    }

    /**
     * 获取部门下的所有员工
     */

    @Override
    public Integer queryUserCountByDepartmentIds(List<Long> departmentIds) {
        //健壮性判断departmentIds是否就查看顶级部门
        if (CollectionUtil.isEmpty(departmentIds)) {
            return 0;
        }
        //创建一个集合用来封装查到的所有部门
        ArrayList<Long> ids = new ArrayList<>();
        ids.addAll(departmentIds);

        //遍历所有的顶级部门id,查找子级部门id
        for (Long departmentId : departmentIds) {
            this.queryChildrenDepartmentIds(ids,departmentId);
        }
        //统计部门下的所有员工
        LambdaQueryWrapper<SysCompanyUser> companyUserQW = new LambdaQueryWrapper<>();
        companyUserQW.eq(SysCompanyUser::getCompanyId,CurrentUserHolder.get().getCompanyId());
        companyUserQW.in(SysCompanyUser::getDepartmentId,ids);

        //查询所有企业部门下员工id数量
        Integer count = sysCompanyUserMapper.selectCount(companyUserQW);

        return count;
    }


}
